package com.itheima.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.itheima.config.OSSConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * @Author HeiMa-sw
 * @Description OSS对象存储//TODO 17210
 * @Date 20:15 2022/6/3
 **/
@Service
@Slf4j
@SpringBootConfiguration
public class OSSService {
    String url = "http://itheimasw.oss-cn-shenzhen.aliyuncs.com";
    @Autowired
    private OSSConfiguration ossConfiguration;

    public String uploadFile(MultipartFile file) {
        final OSS ossClient = ossConfiguration.initOSSClient();
        String fileName = "";
        try {
            fileName = UUID.randomUUID().toString();
            InputStream inputStream = file.getInputStream();
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(file.getContentType());
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            // 上传文件
            ossClient.putObject(ossConfiguration.getBucketName(), fileName, inputStream, objectMetadata);
        } catch (IOException e) {
            log.error("Error occurred: {}", e.getMessage(), e);
        }
        return url+ "/" +fileName;
    }

    public void exportFile(OutputStream os, String objectName) {
        final OSS ossClient = ossConfiguration.initOSSClient();
        OSSObject ossObject = ossClient.getObject(ossConfiguration.getBucketName(), objectName);
        // 读取文件内容
        BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
        BufferedOutputStream out = new BufferedOutputStream(os);
        byte[] buffer = new byte[1024];
        int lenght;
        try {
            while ((lenght = in.read(buffer)) != 0) {
                out.write(buffer, 0, lenght);
            }
            out.flush();
            in.close();
            out.close();
        } catch (IOException e) {
            log.error("Error occurred: {}", e.getMessage(), e);
        }
    }
}
